<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="单据编号" prop="orderCode">
        <el-input
          v-model="queryParams.orderCode"
          placeholder="请输入单据编号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
<!--      <el-form-item label="业务量" prop="businessClassification">-->
<!--        <el-input-->
<!--          v-model="queryParams.businessClassification"-->
<!--          placeholder="请输入业务量"-->
<!--          clearable-->
<!--          size="small"-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
      <el-form-item label="状态" prop="auditResult">
        <el-select v-model="queryParams.auditResult" placeholder="单据状态" clearable size="small">
          <el-option label="待提交" value="0"></el-option>
          <el-option label="待审核" value="1"></el-option>
          <el-option label="审核通过" value="2"></el-option>
          <el-option label="审核拒绝" value="3"></el-option>
          <el-option label="审核中" value="4"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['operation:add']"
        >新增
        </el-button>
      </el-col>
      <!--<el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-check"
          size="mini"
          :disabled="single"
          @click="handleCheck"
          v-hasPermi="['operation:detail']"
        >详情
        </el-button>
      </el-col>-->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="operationList" @selection-change="handleSelectionChange">
      <!--  <el-table-column type="selection" align="center"/>-->
      <el-table-column label="序号" align="center" type="index"/>
      <el-table-column label="单据编号" align="center" prop="orderCode" width="190px"/>
      <el-table-column label="用工日期" align="center" prop="workTime" width="100px"/>
      <el-table-column label="班次" align="center" prop="shiftTimeName"/>
      <el-table-column label="班组" align="center" prop="workGroupName"/>
      <el-table-column label="预估业务量" align="center" prop="predictNumber"/>
      <el-table-column label="启用方案" align="center" prop="enableSchemeName"/>
      <el-table-column label="预估用工量" align="center" prop="estimatedLaborNum"/>
      <el-table-column label="对应标准人员数" align="center" prop="standardNumber"/>
      <!--      <el-table-column label="状态" align="center" prop="status" :formatter="statusFormat" />-->
      <el-table-column label="单据状态" align="center" prop="auditResult">
        <template slot-scope="scope">
          <span v-if="scope.row.auditResult === 0">待提交</span>
          <span v-else-if="scope.row.auditResult === 1">待审核</span>
          <span v-else-if="scope.row.auditResult === 2">审核通过</span>
          <span v-else-if="scope.row.auditResult === 3">审核拒绝</span>
          <span v-else-if="scope.row.auditResult === 4">审核中</span>
          <span v-else>{{ scope.row.auditResult }}</span>
        </template>
      </el-table-column>
      <el-table-column label="审核时间" align="center" prop="auditTime" width="100">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.auditTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="140px" fixed="right">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.auditResult === 2"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleDemandNumberView(scope.row)"
            v-hasPermi="['operation:demandNumber']"
          >实际人数
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleCheck(scope.row)"
            v-hasPermi="['operation:detail']"
          >详情
          </el-button>
          <el-button
            v-if="scope.row.auditResult !== 2 && scope.row.auditResult !== 4"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleEdit(scope.row)"
            v-hasPermi="['operation:edit']"
          >编辑
          </el-button>
          <el-button
            v-if="scope.row.auditResult === 0 || scope.row.auditResult === 3 "
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="submitOperationalAudit(scope.row)"
            v-hasPermi="['operation:audit']"
          >提交审批
          </el-button>
          <el-button
            v-if="scope.row.auditResult === 1 "
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="delOperationalAudit(scope.row)"
            v-hasPermi="['operation:audit']"
          >审核撤销
          </el-button>
          <el-button
            v-if="scope.row.auditResult === 0"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['operation:delete']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改岗位对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="单据编号" prop="orderCode">
          <span>{{ form.orderCode }}</span>
        </el-form-item>
        <el-form-item label="审核结果" prop="auditResult">
          <el-select v-model="form.auditResult" placeholder="请选择" clearable size="small">
            <!--            <el-option label="待审核" value="1"></el-option>-->
            <el-option label="审核通过" value="2"></el-option>
            <el-option label="审核拒绝" value="3"></el-option>
            <el-option label="审核中" value="4"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="title" :visible.sync="demandNumberOpen" width="500px" append-to-body>
      <el-form ref="form" :model="demandNumberForm"  label-width="80px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="用工日期">
              <el-date-picker
                v-model="demandNumberForm.workTime"
                size="mini"
                style="width: 200px"
                value-format="yyyy-MM-dd"
                type="date" disabled
                placeholder="选择日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="实际人数">
              <el-input-number :min="0" v-model="demandNumberForm.demandNumber" ></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitDemandNumberForm">确 定</el-button>
        <el-button @click="demandNumberOpen = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {listPost, getPost, delPost, addPost, updatePost, exportPost} from "@/api/system/post";
import {getOperationalInfo, updateAuditInfo, delOperationalInfo, submitAudit, delAudit,submitDemandNumberForm} from "@/api/operation";

export default {
  name: "Scheme",
  data() {
    return {
      //实际人数表单
      demandNumberOpen:false,
      //实际人数表单
      demandNumberForm:{},
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 运营需求单数据
      operationList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 状态数据字典
      statusOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderCode: undefined,
        businessClassification: undefined,
        schemeName: undefined,
        auditResult: undefined
      },
      //提交审核表单
      auditParam: {
        processInstanceName: undefined,
        businessKey: undefined,
        processDefinitionKey: 'yyxq_audit',
        variables: undefined,
        processType: 1
      },
      //审核撤销
      delAuditParam: {
        taskId: undefined,
        reason: undefined,
        processType: 1,
      },
      //审核参数
      variablesMap: {
        auditFlag: undefined,
        orderCode: undefined
      },
      // 表单参数
      form: {
        id: undefined,
        orderCode: undefined,
        auditResult: undefined
      },
      // 表单校验
      rules: {
        auditResult: [
          {required: true, message: "请选择审核结果", trigger: "change"}
        ],
      }
    };
  },
  created() {
    this.getList();
    this.getDicts("sys_normal_disable").then(response => {
      this.statusOptions = response.data;
    });
  },
  methods: {
    /** 查询岗位列表 */
    getList() {
      this.loading = true;
      getOperationalInfo(this.queryParams).then(response => {
        // console.log(response)
        this.operationList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 岗位状态字典翻译
    statusFormat(row, column) {
      return this.selectDictLabel(this.statusOptions, row.status);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        postId: undefined,
        postCode: undefined,
        postName: undefined,
        postSort: 0,
        status: "0",
        remark: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length != 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.$router.push({path: "/operationManagement/need/add"});

    },
    /** 详情按钮操作 */
    handleEdit(row) {
      // console.log(row);
      this.$router.push({
        path: "/operationManagement/need/edit",
        query: {id: row.id, enableSchemeId: row.enableSchemeId}
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const postId = row.postId || this.ids
      getPost(postId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改岗位";
      });
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // console.log(valid,this.form);
          const params = {
            id: this.form.id,
            auditResult: this.form.auditResult
          }
          // console.log(params)
          //审核
          this.updateAuditInfo(params);
          // updateAuditInfo().then(res=>{
          //   console.log(res)
          // })
        }
      });
    },
    updateAuditInfo(params) {
      updateAuditInfo(params).then(res => {
        // console.log(res);
        if (res.code === 200) {
          this.msgSuccess(res.msg);
          this.open = false;
          //重新获取列表
          this.queryParams.pageNum = 1;
          this.getList()
        } else {
          this.msgError(res.msg || '审核提交错误')
        }
      })
    },
    /** 详情按钮操作 */
    handleCheck(row) {
      const id = row.id || this.ids[0];
      let enableSchemeId = null;
      this.operationList.forEach(item => {
        if (item.id === id) {
          enableSchemeId = item.enableSchemeId;
        }
      })
      // console.log(id)
      this.$router.push({path: "/operationManagement/need/detail", query: {id: id, enableSchemeId: enableSchemeId}});
    },
    /** 审核按钮操作 */
    handleAudit(row) {
      this.title = "运营需求单审核";
      this.open = true;
      this.form = {
        ...this.form,
        id: row.id,
        orderCode: row.orderCode,
      }
      // console.log(row)
    },
    /**提交审核**/
    submitOperationalAudit(row) {
      this.loading = true;
      let standardNumberLimit =(row.standardNumber/row.businessClassification)* row.predictNumber;
      let standardNumberLimitResult = standardNumberLimit* (1 + row.controlRatio / 100);
      let estimatedLaborNumber = row.estimatedLaborNum;
      let flowFlag = estimatedLaborNumber > standardNumberLimitResult ? 1 : 0;
      console.log(standardNumberLimit)
      console.log(estimatedLaborNumber)
      console.log(standardNumberLimitResult);
      this.variablesMap.auditFlag = flowFlag;
      this.variablesMap.orderCode = row.orderCode;
      this.auditParam.businessKey = row.id;
      this.auditParam.processInstanceName = row.workTime + " 运营需求单";
      this.auditParam.variables = this.variablesMap;
      submitAudit(this.auditParam).then(res => {
        this.loading = false;
        if (res.code === 200) {
          this.msgSuccess(res.msg || '审核提交成功');
          this.getList();
        } else {
          this.msgError(res.msg || '审核提交错误');
        }
      })
    },
    /**审核撤回**/
    delOperationalAudit(row) {
      this.loading = true;
      this.delAuditParam.taskId = row.id;
      this.delAuditParam.reason = "任务撤销";
      delAudit(this.delAuditParam).then(res => {
        this.loading = false;
        if (res.code === 200) {
          this.msgSuccess(res.msg || '审核撤销成功');
          this.getList();
        } else {
          this.msgError(res.msg || '审核撤销错误');
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      const _this = this;
      this.$confirm('是否确认删除需求单编号为"' + ids + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        const params = typeof ids === 'object' ? ids : [ids];
        _this.delOperationalInfo(params);
      }).catch((e) => {
        console.log(e)
      });
    },
    //删除接口
    delOperationalInfo(ids) {
      delOperationalInfo(ids).then(res => {
        this.getList();
        this.msgSuccess("删除成功");
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有岗位数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.exportLoading = true;
        return exportPost(queryParams);
      }).then(response => {
        this.download(response.msg);
        this.exportLoading = false;
      }).catch(() => {
      });
    },
    //控制打开界面
    handleDemandNumberView(row){
      console.log("row",row)
      this.demandNumberOpen = true;
      this.title = '实际人数表单';
      this.demandNumberForm = {
        id:row.id,
        workTime:row.workTime,
        demandNumber:row.demandNumber,
      }
    },
    //提交实际用工人数表单
    submitDemandNumberForm(){
      this.loading = true;
      console.log("this.demandNumberForm",this.demandNumberForm)
      submitDemandNumberForm(this.demandNumberForm).then(res => {
        this.loading = false;
        if (res.code === 200) {
          this.msgSuccess(res.msg || '提交成功');
          this.getList();
          this.demandNumberOpen = false;
        } else {
          this.msgError(res.msg || '提交错误');
        }
      })
    },
  }
};
</script>
